package com.mspbots.rule.exceptions.cw;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.cw.request.TenantTimeEntryDTO;
import lombok.extern.slf4j.Slf4j;
import org.jeasy.rules.annotation.Condition;
import org.jeasy.rules.annotation.Fact;
import org.jeasy.rules.annotation.Rule;

import java.util.Map;

/**
 * com.mspbots.rule.exceptions.timeentry.NoAgreementAttached
 *
 * @author Jun Zhou
 * @date 14:37 2019/7/1
 **/
@Slf4j
@Rule(name = "NoAgreementAttached", description = "Dear [user] Please review the time log since it has no agreement attached.")
public class NoAgreementAttached extends CwBaseRule implements IcwBaseRule {


    @Condition
    @Override
    public boolean condition(@Fact(FACT) TenantTimeEntryDTO entry) {
        try {
            if (!setUserMapping(entry.getTenantUserId())) {
                return false;
            }
            if (super.checkMessage(entry)) {
                return false;
            }

            if (!entry.getExtend().has("company")) {
                return false;
            }

            String companyId = entry.getExtend().findPath("company").get("id").asText();

            Map<String, Object> params = Map.of("tenantId", entry.getTenantId(), "companyId", companyId);

            try {
                JsonNode agreement = this.wiseClient.get("/companies/agreement", params).block();
            } catch (Exception e) {
                return false;
            }

            log.info("agreement_{}", entry.getExtend().has("agreement"));

            return !entry.getExtend().has("agreement");
        } catch (Exception e) {
            log.error("NoAgreementAttached rule execute error [{}] : {}", e.getStackTrace()[0].getLineNumber(), e.getMessage());
        }
        return false;
    }


}
